<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="单据号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入单据号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物流单号" prop="logisticsNo">
        <el-input
          v-model="queryParams.logisticsNo"
          placeholder="请输入物流单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物流公司" prop="logisticsCompanyId">
        <el-select v-model="queryParams.logisticsCompanyId" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in logisticsCompany" :key="index" :label="item.name"
                     :value="item.id" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发货人" prop="deliveryBy">
        <el-select v-model="queryParams.deliveryBy" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.userName"
                     :value="item.userId" ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发货时间" prop="deliveryTime">
        <el-date-picker clearable
                        v-model="queryParams.deliveryMinTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '45%'}">
        </el-date-picker>
        <span style="margin: 0 10px">至</span>
        <el-date-picker clearable
                        v-model="queryParams.deliveryMaxTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '45%'}">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="操作人" prop="createBy">
        <el-select v-model="queryParams.createBy" placeholder="全部" clearable :style="{width: '100%'}">
          <el-option v-for="(item, index) in user" :key="index" :label="item.userName"
                     :value="item.userId" ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="操作时间" prop="createTime">
        <el-date-picker clearable
                        v-model="queryParams.createMinTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '45%'}">
        </el-date-picker>
        <span style="margin: 0 10px">至</span>
        <el-date-picker clearable
                        v-model="queryParams.createMaxTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        :style="{width: '45%'}">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:TblLogisticsSheet:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:TblLogisticsSheet:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:TblLogisticsSheet:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:TblLogisticsSheet:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="TblLogisticsSheetList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="单据号" align="center" prop="code" width="180"/>
      <el-table-column label="物流单号" align="center" prop="logisticsNo" />
      <el-table-column label="物流公司" align="center" prop="baseDataLogisticsCompany.name" width="150"/>
      <el-table-column label="总重量" align="center" prop="totalWeight" />
      <el-table-column label="总体积" align="center" prop="totalVolume" />
      <el-table-column label="物流费" align="center" prop="totalAmount" />
      <el-table-column label="操作时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="createBy" width="100"/>
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span>{{ scope.row.status === 0 ? '待发货' : '已发货' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货时间" align="center" prop="deliveryTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="发货人" align="center" prop="deliveryBy" width="100"/>
      <el-table-column label="备注" align="center" prop="description" />
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button
            size="medium"
            type="text"
            @click="selectLogisticsSheet(scope.row)"
            v-hasPermi="['system:PurchaseOrder:edit']"
          >查看</el-button>
          <el-button
            size="medium"
            type="text"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status === 0"
          >修改</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.status === 0"
            @click="delivery(scope.row)"
          >发货</el-button>
          <el-button
            size="medium"
            type="text"
            v-if="scope.row.status === 0"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看按钮 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <div style="border: 1px gainsboro solid;padding: 10px 10px 10px 30px">
        <div style="display: inline-block;width: 300px;"><p>单据号：{{ this.form.code }}</p></div>
                <div style="display: inline-block;width: 300px;"><p>状态：<span>{{ this.form.status==0 ? '待审核' : (this.form.status==3 ? '审核通过' : '审核拒绝') }}</span></p></div>
        <br>
        <div style="display: inline-block;width: 300px;"><p>操作人：{{ this.form.createBy }}</p></div>
        <div style="display: inline-block;width: 300px;"><p>操作时间：{{ this.form.createTime }}</p></div>
      </div>
      <div style="border: 1px gainsboro solid;margin-top: 5px">
        <el-table v-loading="loading" :data="this.tblLogisticsSheetDetailList" @selection-change="handleSelectionChange">
          <el-table-column label="业务单据号" align="left" prop="tblSaleOutSheet.code" width="200px"/>
          <el-table-column label="业务类型" align="left" prop="bizType" width="180">
            <template slot-scope="scope">
              <span>{{ '销售出库单'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="仓库名称" align="left" prop="tblSaleOutSheet.scName" width="100px"/>
          <el-table-column label="收件人" align="left" prop="tblSaleOutSheet.customerName" width="100px"/>
          <el-table-column label="操作时间" align="left" prop="tblSaleOutSheet.createTime" width="250px"/>
          <el-table-column label="操作人" align="left" prop="tblSaleOutSheet.createBy" width="100px"/>
        </el-table>
      </div>

      <el-form :model="form" ref="" size="small" :inline="true" label-width="80px">
        <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
          <h3 style="margin:0 0 15px 10px;font-weight: bolder;">寄件人信息</h3>
          <el-form-item label="姓名" prop="senderName">
            <el-input
              v-model="form.senderName"
              clearable
            />
          </el-form-item>
          <el-form-item label="联系电话" prop="senderTelephone">
            <el-input
              v-model="form.senderTelephone"
              clearable
            />
          </el-form-item>
          <el-form-item label="地区" prop="senderValue">
            <el-cascader
               v-model="form.senderValue"
               :options="options1"
               :props="{
                value:'id',
                label:'name',
                children:'children',expandTrigger: 'hover',
              }"
           />
          </el-form-item>
          <el-form-item label="详细地址" prop="senderAddress">
            <el-input
              type="textarea"
              :rows="2"
              v-model="form.senderAddress"
              style="width: 800px;"
            />
          </el-form-item>
        </div>

        <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
          <h3 style="margin:0 0 15px 10px;font-weight: bolder;">收件人信息</h3>
          <el-form-item label="姓名" prop="receiverName">
            <el-input
              v-model="form.receiverName"
              clearable
            />
          </el-form-item>
          <el-form-item label="联系电话" prop="receiverTelephone">
            <el-input
              v-model="form.receiverTelephone"
              clearable
            />
          </el-form-item>
          <el-form-item label="地区" prop="receiverValue">
            <el-cascader
              v-model="form.receiverValue"
              :options="options1"
              :props="{
                value:'id',
                label:'name',
                children:'children',expandTrigger: 'hover',
              }"
            />
          </el-form-item>
          <el-form-item label="详细地址" prop="receiverAddress">
            <el-input
              type="textarea"
              :rows="2"
              v-model="form.receiverAddress"
              style="width: 800px;"
            />
          </el-form-item>
        </div>

        <div style="border: 1px gainsboro solid;margin-top: 5px;padding: 10px">
          <h3 style="margin:0 0 15px 10px;font-weight: bolder;">物流单信息</h3>
          <el-form-item label="物流公司" prop="code">
            <el-input
              v-model="form.logisticsCompany.name"
              clearable
            />
          </el-form-item>
          <el-form-item label="物流单号" prop="logisticsNo">
            <el-input
              v-model="form.logisticsNo"
              clearable
            />
          </el-form-item>
          <el-form-item label="总重量(kg)" prop="totalWeight">
            <el-input
              v-model="form.totalWeight"
              clearable
            />
          </el-form-item>
          <el-form-item label="总体积(kg)" prop="code">
            <el-input
              v-model="form.totalVolume"
              clearable
            />
          </el-form-item>
          <el-form-item label="物流费(元)" prop="totalAmount">
            <el-input
              v-model="form.totalAmount"
              clearable
            />
          </el-form-item>
          <el-form-item label="备注" prop="description">
            <el-input
              type="textarea"
              :rows="2"
              v-model="form.description"
              style="width: 800px;"
            />
          </el-form-item>
        </div>
      </el-form>
    </el-dialog>

<!--     发货 -->
      <el-dialog title="发货" :visible.sync="deliveryOpen" width="500px" append-to-body>
        <el-form ref="deliveryForm" :model="deliveryForm" :rules="deliveryRules" label-width="80px">
          <el-form-item label="物流单号" prop="logisticsNo">
            <el-input type="text" v-model="deliveryForm.logisticsNo" placeholder="请输入物流单号" />
          </el-form-item>
          <el-form-item label="物流费" prop="totalAmount">
            <el-input type="text" v-model="deliveryForm.totalAmount" placeholder="请输入物流费" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: center">
          <el-button type="primary" @click="deliverySubmit">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
import { listTblLogisticsSheet, getTblLogisticsSheet, delTblLogisticsSheet, addTblLogisticsSheet, updateTblLogisticsSheet } from "@/api/system/TblLogisticsSheet";
import { listUser } from "@/api/system/user"
import {getLogisticsCompany, listLogisticsCompany} from "@/api/system/LogisticsCompany";
import {listCity} from "@/api/system/City";
import {listReceiveSheet} from "@/api/system/ReceiveSheet";

export default {
  name: "TblLogisticsSheet",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedTblLogisticsSheetDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物流单表格数据
      TblLogisticsSheetList: [],
      // 物流单明细表格数据
      tblLogisticsSheetDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        logisticsNo: null,
        logisticsCompanyId: null,
        status: null,
        deliveryBy: null,
        deliveryTime: null,
        createById: null,
        createTime: null,
      },
      // 表单参数
      form: {
        logisticsCompany:{
          nama:""
        }
      },
      // 表单校验
      rules: {
      },

      // 物流公司
      logisticsCompany: [],
      // 操作人、发货人
      user: [],

      //发货
      deliveryOpen:false,
      deliveryForm: {
        id:null,
        logisticsNo: '',
        totalAmount: ''
      },
      deliveryRules: {
        logisticsNo: [
          { required: true, message: "物流单号不能为空", trigger: "blur" }
        ],
        totalAmount: [
          { required: true, message: "物流费不能为空", trigger: "blur" }
        ]
      },

      //地区
      options1:[],

    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物流单列表 */
    getList() {
      this.loading = true;
      listTblLogisticsSheet(this.queryParams).then(response => {
        this.TblLogisticsSheetList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      listUser(this.user).then(response => {
        this.user = response.rows;
      });
      listLogisticsCompany().then(response => {
        this.logisticsCompany = response.rows;
      })
    },
    // 取消按钮
    cancel() {
      this.deliveryOpen=false;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        logisticsCompany:{
          nama:""
        }
      };
      this.tblLogisticsSheetDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.$router.push({
        path:'/TblLogisticsSheet/add',
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.$router.push({
        path:'/TblLogisticsSheet/update',
        query:{
          id: id,
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.tblLogisticsSheetDetailList = this.tblLogisticsSheetDetailList;
          if (this.form.id != null) {
            updateTblLogisticsSheet(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTblLogisticsSheet(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物流单编号为"' + ids + '"的数据项？').then(function() {
        return delTblLogisticsSheet(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 物流单明细序号 */
    rowTblLogisticsSheetDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 物流单明细添加按钮操作 */
    handleAddTblLogisticsSheetDetail() {
      let obj = {};
      obj.bizId = "";
      obj.bizType = "";
      this.tblLogisticsSheetDetailList.push(obj);
    },
    /** 物流单明细删除按钮操作 */
    handleDeleteTblLogisticsSheetDetail() {
      if (this.checkedTblLogisticsSheetDetail.length == 0) {
        this.$modal.msgError("请先选择要删除的物流单明细数据");
      } else {
        const tblLogisticsSheetDetailList = this.tblLogisticsSheetDetailList;
        const checkedTblLogisticsSheetDetail = this.checkedTblLogisticsSheetDetail;
        this.tblLogisticsSheetDetailList = tblLogisticsSheetDetailList.filter(function(item) {
          return checkedTblLogisticsSheetDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleTblLogisticsSheetDetailSelectionChange(selection) {
      this.checkedTblLogisticsSheetDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/TblLogisticsSheet/export', {
        ...this.queryParams
      }, `TblLogisticsSheet_${new Date().getTime()}.xlsx`)
    },


    // 查看按钮
    async selectLogisticsSheet(row) {
      const id = row.id || this.ids

      try {
        let logisticsCompany = await getLogisticsCompany(row.logisticsCompanyId);
        const response = await getTblLogisticsSheet(id);
        if (response.code === 200){
          this.form=response.data;
          this.tblLogisticsSheetDetailList=response.data.tblLogisticsSheetDetailList;
          this.open = true;
          this.title = "查看";

          this.form.senderValue = [this.form.senderProvinceId, this.form.senderCityId, this.form.senderDistrictId]
          this.form.receiverValue = [this.form.receiverProvinceId, this.form.receiverCityId, this.form.receiverDistrictId]

          this.form.logisticsCompany=logisticsCompany.data

          this.getCityList()
        }
      } catch (error) {
        console.error('获取物流详情失败', error);
      }
    },

    delivery(row) {
      this.deliveryOpen = true;
      this.deliveryForm.id=row.id;
      getTblLogisticsSheet(row.id).then(response => {
        this.deliveryForm.logisticsNo = response.data.logisticsNo;
        this.deliveryForm.totalAmount = response.data.totalAmount;
        this.deliveryForm.tblLogisticsSheetDetailList = response.data.tblLogisticsSheetDetailList;
      });
    },

    //发货
    deliverySubmit() {
      this.$refs["deliveryForm"].validate(valid => {
        if (valid) {
          this.form.status=3;
          this.form.updateById="1"
          this.form.updateBy='系统管理员';
          this.form.deliveryBy='系统管理员';
          this.form.deliveryTime=new Date()
          this.form.id=this.deliveryForm.id
          this.form.logisticsNo=this.deliveryForm.logisticsNo
          this.form.totalAmount=this.deliveryForm.totalAmount
          this.form.tblLogisticsSheetDetailList=this.deliveryForm.tblLogisticsSheetDetailList
          console.log(this.form)
          updateTblLogisticsSheet(this.form).then(response => {
            this.$modal.msgSuccess("发货成功");
            this.deliveryOpen = false;
            this.getList();
          });
        }
      });
    },

    //地区框
    getCityList() {
      listCity(this.queryParams).then(response => {
        this.options1 = response.rows;
      });
    },
  }
  ,beforeRouteEnter(to, from, next) {
    next(vm => {
      // 重新获取数据
      vm.getList();
    });
  }
};
</script>













